import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { prisma } from '@/lib/prisma';
import { authenticateRequest } from '@/utils/auth';
import { createPaginationResponse, parsePaginationParams } from '@/lib/pagination';
import { PaginationResponse } from '@/types/api-common';
import { Prisma } from '@prisma/client';
import { Category } from '@/types/category';

// POST /api/admin/categories/page - 获取分类分页列表
async function handlePost(request: NextRequest): Promise<PaginationResponse<Category>> {
  // 1. 权限验证
  const authResult = await authenticateRequest(request);
  if (!authResult.success) {
    throw new Error(authResult.error || '认证失败');
  }

  // 2. 解析分页和搜索参数
  const body = await request.json();
  const { page, pageSize, skip } = parsePaginationParams(body);
  const { name, menuId } = body;

  // 3. 构建查询条件
  const where: Prisma.CategoryWhereInput = {};
  if (name) {
    where.name = { contains: name };
  }
  if (menuId) {
    where.menuId = menuId;
  }

  // 4. 并行查询数据和总数
  const [items, total] = await Promise.all([
    prisma.category.findMany({
      where,
      include: {
        menu: {
          select: {
            name: true,
          },
        },
      },
      orderBy: {
        createdAt: 'desc',
      },
      skip,
      take: pageSize,
    }),
    prisma.category.count({ where }),
  ]);

  // 5. 数据转换
  const data = items.map(item => ({
    ...item,
    createdAt: item.createdAt.toISOString(),
    updatedAt: item.updatedAt.toISOString(),
    value: item.id,

  }));

  // 6. 返回分页响应
  return createPaginationResponse(data, total, page, pageSize);
}

export const POST = withMiddleware(handlePost);